package com.canbot.u05.activity.guide;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.canbot.u05.R;
import com.canbot.u05.activity.BaseActivityNoTitle;
import com.canbot.u05.bean.JsonResponse;
import com.canbot.u05.glide.GlideApp;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.utils.OkHttpUtils;
import com.canbot.u05.utils.StatusBarUtil;
import com.canbot.u05.utils.ToastTools;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author zmp
 * 导览模式选择底图界面
 */
public class GuideChoosePicActivity extends BaseActivityNoTitle implements View.OnClickListener, AdapterView.OnItemClickListener {

        private String[] picPaths;

        private boolean[] bs;

        private int currentPosition = -1;

        private GridView gridView;

        private ToastTools toastTools;

        private View ivOk;

        private View ivPb;

        private TextView tvLoad;

        private boolean multiple;

        private String picPath;

        private List<String> pathArr;


        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_guide_choose_pic);
                multiple = getIntent().getBooleanExtra("multiple", false);
                if (multiple) {
                        String pathArray = getIntent().getStringExtra("picArray");
                        if (!TextUtils.isEmpty(pathArray)) {
                                pathArr = JSON.parseArray(pathArray, String.class);
                        }
                        else {
                                pathArr = new ArrayList<>();
                        }
                }
                else {
                        picPath = getIntent().getStringExtra("picPath");
                }
                initView();
                initData();
        }

        private void initData() {
                currentPosition = -1;
                showLoadDialog();
                String url = IpMsgConst.HTTP_URL_CHEST + "getAllPic";
                HashMap<String, String> hashMap = new HashMap<>();
                hashMap.put("path", "/uupic");
                OkHttpUtils.upLoadFile(url, hashMap, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(String result) {
                                loadDialog.dismiss();
                                JsonResponse jsonResponse = new Gson().fromJson(result, JsonResponse.class);
                                if (jsonResponse != null) {
                                        if (jsonResponse.getRc() == -1) {
                                                toastTools.showText("请求参数错误！");
                                                return;
                                        }
                                        Type type = new TypeToken<String[]>() {
                                        }.getType();
                                        picPaths = new Gson().fromJson(jsonResponse.getResult().toString(), type);
                                        if (picPaths == null || picPaths.length == 0) {
                                                toastTools.showText("没有可选背景");
                                                return;
                                        }
                                        bs = new boolean[picPaths.length];
                                        initPath();
                                        runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                        myBaseAdapter.notifyDataSetChanged();
                                                }
                                        });

                                }
                                else {
                                        toastTools.showText("服务器异常!");
                                }
                        }

                        @Override
                        public void onFailure() {
                                loadDialog.dismiss();
                                toastTools.showText("服务器异常!");
                        }
                });
        }

        private void initPath() {
                if (multiple) {
                        if (pathArr != null && pathArr.size() > 0) {
                                for (int i = 0; i < picPaths.length; i++) {
                                        if (pathArr.contains(picPaths[i])) {
                                                bs[i] = true;
                                        }
                                }
                        }
                }
                else {
                        if (!TextUtils.isEmpty(picPath)) {
                                for (int i = 0; i < picPaths.length; i++) {
                                        if (picPath.contains(picPaths[i])) {
                                                currentPosition = i;
                                                bs[currentPosition] = true;
                                                break;
                                        }
                                }
                        }
                }
        }

        private void initView() {
                toastTools = ToastTools.newInstance(this);
                findViewById(R.id.main_iv_back).setOnClickListener(this);
                findViewById(R.id.save_bt).setOnClickListener(this);
                gridView = (GridView) findViewById(R.id.choose_pic_gv);
                gridView.setAdapter(myBaseAdapter);
                gridView.setOnItemClickListener(this);
        }

        @Override
        public void onClick(View v) {
                switch (v.getId()) {
                        case R.id.main_iv_back:
                                setResult(RESULT_CANCELED);
                                finish();
                                break;
                        case R.id.save_bt:
                                if (multiple){
                                        if (pathArr==null||pathArr.size()==0){
                                                toastTools.showText("请先选择要显示的底图");
                                        }else {
                                                Intent intent = new Intent().putExtra("picArray", JSON.toJSONString(pathArr));
                                                setResult(RESULT_OK, intent);
                                                finish();
                                        }
                                }else {
                                        if (currentPosition == -1) {
                                                toastTools.showText("请先选择要显示的底图");
                                                return;
                                        }
                                        Intent intent = new Intent().putExtra("picPath", picPaths[currentPosition]);
                                        setResult(RESULT_OK, intent);
                                        finish();
                                }
                                break;
                }

        }


        private Dialog loadDialog;

        private void showLoadDialog() {
                if (loadDialog == null) {
                        loadDialog = new Dialog(this, R.style.MyDialogStyle);
                        loadDialog.setContentView(R.layout.guide_dialog_load);
                        ivOk = loadDialog.findViewById(R.id.guide_load_iv);
                        ivPb = loadDialog.findViewById(R.id.guide_load_pb);
                        tvLoad = (TextView) loadDialog.findViewById(R.id.guide_load_tv);
                }
                ivPb.setVisibility(View.VISIBLE);
                ivOk.setVisibility(View.INVISIBLE);
                tvLoad.setText("正在加载...");
                loadDialog.setCancelable(false);
                StatusBarUtil.hideVirtualKey(loadDialog);
                loadDialog.show();
        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.e("test", "onItemClick" + position);
                if (multiple) {
                        bs[position] = !bs[position];
                        if (bs[position]) {
                                pathArr.add(picPaths[position]);
                        }else {
                                pathArr.remove(picPaths[position]);
                        }
                }else {
                        if (currentPosition != -1) {
                                bs[currentPosition] = false;
                        }
                        currentPosition = position;
                        bs[position] = true;
                }
                myBaseAdapter.notifyDataSetChanged();
        }


        BaseAdapter myBaseAdapter = new BaseAdapter() {
                @Override
                public int getCount() {
                        return picPaths == null ? 0 : picPaths.length;
                }

                @Override
                public Object getItem(int position) {
                        return position;
                }

                @Override
                public long getItemId(int position) {
                        return position;
                }

                @Override
                public View getView(int position, View convertView, ViewGroup parent) {
                        if (convertView == null) {
                                LayoutInflater inflater = LayoutInflater.from(GuideChoosePicActivity.this);
                                convertView = inflater.inflate(R.layout.guide_choose_pic_item, parent, false);
                                Holder holder = new Holder(convertView);
                                convertView.setTag(holder);
                        }
                        Holder holder = ((Holder) convertView.getTag());
                        holder.setData(position);
                        return convertView;
                }
        };

        class Holder {

                private final TextView textView;

                private final ImageView checkIv;

                private final ImageView imageView;

                public Holder(View inflate) {
                        textView = (TextView) inflate.findViewById(R.id.tv);
                        checkIv = (ImageView) inflate.findViewById(R.id.cb);
                        imageView = (ImageView) inflate.findViewById(R.id.iv);
                }

                public void setData(int position) {
                        if (picPaths[position].contains("/uupic/")) {
                                textView.setText(picPaths[position].replace("/uupic/", ""));
                        }
                        else {
                                textView.setText(picPaths[position]);
                        }
                        checkIv.setVisibility(bs[position] ? View.VISIBLE : View.GONE);
                        checkIv.setTag(position);
                        checkIv.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                        int tag = (Integer) checkIv.getTag();
                                        if (currentPosition == tag && bs[currentPosition]) {
                                                bs[currentPosition] = false;
                                                currentPosition = -1;
                                                myBaseAdapter.notifyDataSetChanged();
                                                return;
                                        }
                                        if (currentPosition != -1) {
                                                bs[currentPosition] = false;
                                        }
                                        currentPosition = tag;
                                        bs[currentPosition] = true;
                                        myBaseAdapter.notifyDataSetChanged();
                                }
                        });
                        GlideApp.with(GuideChoosePicActivity.this).clear(imageView);
                        GlideApp.with(GuideChoosePicActivity.this)
                                .asDrawable()
                                .load(IpMsgConst.HTTP_URL_CHEST + picPaths[position].replace("/uupic/","/uupic_thumb/"))
                                .thumbnail(0.1f)
                                .diskCacheStrategy(DiskCacheStrategy.ALL)//缓存策略
                                .skipMemoryCache(false)
                                .placeholder(R.drawable.sales_banner01)//占位图
                                .error(R.drawable.sales_banner01)
                                .override(100, 100)
                                .into(imageView);
                }
        }
}
